<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NButton, NModal, NForm, NFormItem, NInput, NSelect, useMessage } from 'naive-ui';
import { getClientList, createClient, updateClient, deleteClient, getClientDetail } from '#/api/authserver/client';

const columns = [
  { key: 'id', title: '客户端ID' },
  { key: 'domain', title: '域名' },
  { key: 'grant_types', title: '授权类型', render: (row: any) => (row.grant_types || []).join(', ') },
  { key: 'scopes', title: '作用域', render: (row: any) => (row.scopes || []).join(', ') },
  { key: 'public', title: '公开', render: (row: any) => row.public ? '是' : '否' },
  { key: 'user_id', title: '用户ID' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref([]);
const loading = ref(false);
const message = useMessage();

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'>('create');
const modalTitle = ref('');
const formModel = ref<any>({});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getClientList();
    data.value = res.clients || [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建客户端';
  formModel.value = { public: 'false' };
  showModal.value = true;
}

function handleEdit(row: any) {
  modalType.value = 'edit';
  modalTitle.value = '编辑客户端';
  formModel.value = {
    ...row,
    grant_types: (row.grant_types || []).join(','),
    scopes: (row.scopes || []).join(','),
    public: row.public ? 'true' : 'false'
  };
  showModal.value = true;
}

async function handleDetail(row: any) {
  modalType.value = 'detail';
  modalTitle.value = '客户端详情';
  formLoading.value = true;
  try {
    const res = await getClientDetail(row.id);
    console.log('Detail API Response:', res);

    // 适配新的 API 响应格式
    if (res.client) {
      const client = res.client;
      formModel.value = {
        id: client.ID,
        domain: client.Domain,
        secret: client.Secret,
        public: client.Public,
        user_id: client.UserID,
        grant_types: client.GrantTypes || [],
        scopes: client.Scopes || [],
        created_at: client.CreatedAt,
        created_by: client.CreatedBy,
        deleted_at: client.DeletedAt
      };
    } else {
      // 兼容旧格式
      formModel.value = res.result || {};
    }

    // 转换为表格数据格式
    detailData.value = [
      { field: '客户端ID', value: formModel.value.id || '-' },
      { field: '域名', value: formModel.value.domain || '-' },
      { field: '授权类型', value: Array.isArray(formModel.value.grant_types) ? formModel.value.grant_types.join(', ') : formModel.value.grant_types || '-' },
      { field: '作用域', value: Array.isArray(formModel.value.scopes) ? formModel.value.scopes.join(', ') : formModel.value.scopes || '-' },
      { field: '公开', value: formModel.value.public === true || formModel.value.public === 'true' ? '是' : '否' },
      { field: '密钥', value: formModel.value.secret || '-' },
      { field: '用户ID', value: formModel.value.user_id || '-' },
      { field: '创建时间', value: formModel.value.created_at || '-' },
      { field: '创建者', value: formModel.value.created_by || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}

async function handleDelete(row: any) {
  if (confirm('确定要删除该客户端吗？')) {
    await deleteClient(row.id);
    message.success('删除成功');
    fetchData();
  }
}

function getProcessedFormModel() {
  const model = { ...formModel.value };

  if (typeof model.grant_types === 'string') {
    model.grant_types = model.grant_types.split(',').map((v: string) => v.trim()).filter(Boolean);
  }

  if (typeof model.scopes === 'string') {
    model.scopes = model.scopes.split(',').map((v: string) => v.trim()).filter(Boolean);
  }

  model.public = model.public === 'true' || model.public === true;

  return model;
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    const processedModel = getProcessedFormModel();
    if (modalType.value === 'create') {
      await createClient(processedModel);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      await updateClient(processedModel.id, processedModel);
      message.success('编辑成功');
    }
    showModal.value = false;
    fetchData();
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="客户端管理" title="客户端管理">
    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建客户端</NButton>
    </div>
    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '800px' }">
      <NForm :model="formModel" label-width="100" v-if="modalType !== 'detail'">
        <NFormItem label="客户端ID" path="id">
          <NInput v-model:value="formModel.id" :disabled="modalType==='edit'" />
        </NFormItem>
        <NFormItem label="域名" path="domain">
          <NInput v-model:value="formModel.domain" />
        </NFormItem>
        <NFormItem label="授权类型" path="grant_types">
          <NInput v-model:value="formModel.grant_types" placeholder="用英文逗号分隔" />
        </NFormItem>
        <NFormItem label="作用域" path="scopes">
          <NInput v-model:value="formModel.scopes" placeholder="用英文逗号分隔" />
        </NFormItem>
        <NFormItem label="公开" path="public">
          <NSelect v-model:value="formModel.public" :options="[{label:'是',value:'true'},{label:'否',value:'false'}]" />
        </NFormItem>
        <NFormItem label="密钥" path="secret">
          <NInput v-model:value="formModel.secret" type="password" show-password-on="click" />
        </NFormItem>
        <NFormItem label="用户ID" path="user_id">
          <NInput v-model:value="formModel.user_id" />
        </NFormItem>
      </NForm>
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />
      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
